﻿package net.wangit.dev.table;

import net.wangit.Element;
import net.wangit.MapList;
import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.dev.ConsoleDomainUtil;
import net.wangit.dev.LockUtil;
import net.wangit.framework.config.DomainsSettings;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.DBFactory;
import net.wangit.jdbc.DBImplementor;
import net.wangit.jdbc.database.Database;
import net.wangit.jdbc.table.TableMetaFactory;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.support.UnitInterceptor;
import net.wangit.util.Checker;
import net.wangit.view.enumeration.EnumerationUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class TableUI implements UnitInterceptor {

	private static final Log log = LogFactory
			.getLog(net.wangit.dev.table.TableUI.class);
	public static final String KEY = "net.wangit.dev.table.TableUI.tablename";
	private static final String CSS_INVALID = "invalid";
	private static final String SQL_TABLE = "select * from TABLE where t=?";
	protected static final String SQL_COLUMN = "select * from COLUMN where t=? order by o";
	private static final String SQL_VERSION = "select c as value,c+' - '+cl as name from COLUMN where t=? and v=1 order by o";

	public TableUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		String domain = ConsoleDomainUtil.getDomain(ac);
		String source = ac.getRequestParameter("src");
		boolean copy = !Checker.isEmpty(source);
		String tableName = copy ? source : ActionContextHelper
				.getRequest2Session(ac, "tablename", TableUI.KEY, null);
		Element versionColumn = unit.getElement("vc");
		if (versionColumn != null)
			versionColumn.setObject(EnumerationUtil.getBlankEnumeration());
		String unitShowMode = unit.getShowMode();
		if ("a".equals(unitShowMode) || tableExistent(domain, tableName)
				|| !hasPrimaryKey(domain, tableName))
			unit.removeElement("create");
		Unit c = (Unit) unit.getElement("column").getObject();
		if (!copy && "a".equals(unitShowMode)) {
			String groupId = ac.getRequestParameter("groupid");
			unit.getElement("gid").setDefaultValue(groupId);
		} else if (unit.getData() == null) {
			DB db = DBHelper.getDomainDB(domain);
			MapList tableData = db.query(TableUI.SQL_TABLE, tableName, 2);
			MapList columnData = db.query(TableUI.SQL_COLUMN, tableName, 2);
			unit.setData(tableData);
			unit.setData(tableData);
			setColumnData(c, columnData);
			if (versionColumn != null)
				versionColumn.setObject(getVersionColumnEnumeration(db,
						tableName));
			if (copy) {
				tableData.put(0, "t", "");
				tableData.put(0, "l", "0");
			}
		}
		LockUtil.setElements(ac, unit, new Object[][] {
				new Object[] { unit, "create", "save" },
				new Object[] { c, "add", "remove" } });
		if ("a".equals(unitShowMode))
			c.removeElement("excel");
		return unit.write(ac);
	}

	private void setColumnData(Unit columnUnit, MapList data) {
		columnUnit.setData(data);
		if (!Checker.isEmpty(data)) {
			for (int i = 0; i < data.size(); i++) {
				int valid = data.getRow(i).getInt("v", 1);
				if (valid == 0)
					columnUnit.setRowCss(i, TableUI.CSS_INVALID);
			}

		}
	}

	private boolean tableExistent(String domain, String tableName) {
		DBImplementor actionDB;
		Database database;
		try {
			actionDB = (DBImplementor) DBFactory.getDB(DomainsSettings
					.getDatasource(domain));
			database = actionDB.getJDBCSettings().getDatabase();
			return database.tableExistent(actionDB, tableName);
		} catch (Exception e) {
			return false;
		}
	}

	private boolean hasPrimaryKey(String domain, String tableName) {
		try {
			TableMetaFactory.getTableMeta(domain, tableName);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	private MapList getVersionColumnEnumeration(DB db, String tableName) {
		try {
			MapList list = db.query(TableUI.SQL_VERSION, tableName, 2);
			if (Checker.isEmpty(list))
				return EnumerationUtil.getBlankEnumeration();
			list.insertRow(0, EnumerationUtil.getBlankRow());
			return list;
		} catch (Exception e) {
			log.error((new StringBuilder("create Enumeration failed:")).append(
					e).toString());
			return null;
		}
	}

}
